//
// Created by 高森森 on 2022/1/27.
//

#ifndef LEETCODE_SOLUTION10_H
#define LEETCODE_SOLUTION10_H
#include<queue>
#include <iostream>
using namespace std;
struct TreeNode {
         int val;
        TreeNode *left;
        TreeNode *right;
        TreeNode() : val(0), left(nullptr), right(nullptr) {}
         TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
         TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution10 {
public:
    int count=0;
public:
    void dfs(TreeNode* grandparent ,TreeNode* parent,TreeNode*node){
        if(node== nullptr)
        {
            return;
        }
        if(grandparent->val%2==0)
        {
            count+=node->val;
        }
        dfs(parent,node,node->left);
        dfs(parent,node,node->right);
    }
    int sumEvenGrandparent(TreeNode* root) {
      if(root->left)
      {
          dfs(root,root->left,root->left->left);
          dfs(root,root->left,root->left->right);
      }
      if(root->right)
      {
          dfs(root,root->right,root->right->left);
          dfs(root,root->right,root->right->right);
      }
    };
    int sumEvenGrandparent2(TreeNode* root) {
        queue<TreeNode*>que;
        que.push(root);
        while(!que.empty())
        {
            TreeNode * node =que.front();
            que.pop();
            if(node->val%2==0)
            {
                if(node->left)
                {
                    if(node->left->left)
                    {
                        count+=node->left->left->val;
                    }
                    if(node->left->right)
                    {
                        count+=node->left->right->val;
                    }
                }
                if(node->right)
                {
                    if(node->right->left)
                    {
                        count+=node->right->left->val;
                    }
                    if(node->right->right)
                    {
                        count+=node->right->right->val;
                    }
                }
            }
            if(node->left)
                que.push(node->left);
            if(node->right)
                que.push(node->right);
        }
        return count;
    }
};


#endif //LEETCODE_SOLUTION10_H
